<template>
  <div>
    <div class="common_title">
        <span style="font-size:20px;font-weight:bold">角色管理</span>
      </div>
    <!-- 查询框 -->
    <div class="query_bg">
        <!-- <span class="query_bg_username">
          <el-input placeholder="角色名" v-model="input" :size="size" style="width:200px"> </el-input>
        </span> -->
        <!-- <span class="query_bg_button" style="margin-left:20px">
          <el-button type="goon" icon="el-icon-search" :size="size" @click="findByName">查询</el-button>
        </span> -->
        <span class="query_bg_addData" style="margin-left:20px">
            <el-button type="goon" icon="el-icon-plus" @click="addRoleClick" :size="size">新增</el-button>
        </span>
        <div class="grid-content bg-purple-light"></div>
    </div>
    <!-- <hr style='border:0.5px inset #FAFAFA;'> -->
    <!-- 数据列表框 -->
    <div  class="dataList_bg">
      <div class="dataList">
        <el-table ref="multipleTable" size="size" :data="tableData" tooltip-effect="dark" style="width: 100%" :default-sort = "{prop: 'id', order: 'descending'}">
            <el-table-column header-align="center" align="center" width="120" label="序号" sortable>
              <template slot-scope="scope">
                <span>{{(page - 1) * perPage + scope.$index + 1}}</span>
              </template>
            </el-table-column>
            <el-table-column prop="roleName" header-align="center" align="center" label="角色名称"></el-table-column>
            <el-table-column prop="roleCreater" header-align="center" align="center" label="创建人"></el-table-column>
            <el-table-column prop="createTime" header-align="center" align="center" label="创建时间"></el-table-column>
            <el-table-column prop="" label="操作" show-overflow-tooltip header-align="center" align="center">
                <template slot-scope="scope">
                  <el-button round size="mini" @click="editRoleClick(scope.row)">编辑</el-button>
                  <el-button round size="mini" @click="modifyClick(scope.row)">权限设置</el-button>
                  <el-button type="danger" round size="mini" @click="deleteRoleClick(scope.row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
      </div>
      <!-- 分页 -->
      <div class="block" style="width:100%;text-align:right;margin-top:10px">
        <el-pagination @size-change="handleperPageChange" @current-change="handleCurrentChange" :current-page="page" :page-sizes="[10, 20, 50]" :page-size="perPage"
          layout="total, sizes, prev, pager, next, jumper" :total="total">
        </el-pagination>
      </div>
      <!--新增编辑界面-->
      <el-dialog :title="operation?'新增角色':'编辑角色'" width="40%" :visible.sync="dialogVisible" :close-on-click-modal="false">
        <el-form :model="dataFormAdd" label-width="80px" :rules="dataFormRules" ref="dataForm" :size="size">
            <el-form-item label="角色名" prop="roleName" style="margin-left:10px">
                <el-input v-model="dataFormAdd.roleName" style="width:300px;"></el-input>
            </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
            <el-button :size="size" @click.native="dialogVisible = false">取消</el-button>
            <el-button :size="size" type="primary"  @click="submitForm()" :loading="editLoading">提交</el-button>
        </div>
      </el-dialog>
      <!-- 授权部分 -->
      <el-dialog title="权限设置" :visible.sync="modifyVisible" width="40%" :before-close="handleClose">
        <div class="shouquan">
        <el-form :inline="true" :model="filters" :size="size" style="margin-top:0px;text-algin:left !important">
          <el-form-item label="是否修改权限:" prop="cmodify" style="font-weight:600;font-size:30px;margin-left:10px">
            <el-radio-group v-model="cmodify" :change="selectRadio()">
              <el-radio-button label="1">否</el-radio-button>
              <el-radio-button label="0">是</el-radio-button>>
            </el-radio-group>
          </el-form-item>
          <!--角色菜单，表格树内容栏-->
          <div class="menu-container" :v-if="true">
            <div class="menu-header">
              <span style="margin-left:10px"> <B>角色菜单授权：</B> </span>
              <span style="margin-left:10px;margin-top:5px">
                <el-form-item>
                  <span v-for="(item,index) in rightData.rightMenuVO.tMenuList" :key="index" class="hang" name="type">
                    {{item.menuName}} :
                    <el-radio-group v-model="dataForm.tMenuList[index].value" v-bind:disabled="modify">
                      <el-radio :label="item.menuId*1000+item2.rightId" v-for="(item2,index2) in rightData.rightMenuVO.tRightList" :key="index2">{{item2.rightName}}</el-radio>
                    </el-radio-group>
                    <br />
                  </span>
                </el-form-item>
              </span>
            </div>
          </div>
          <!--角色功能授权-->
          <div class="menu-container" :v-if="true">
            <div class="menu-header">
              <span style="margin-left:10px"> <B>角色功能授权：</B>  </span>
              <span style="margin-left:10px;margin-top:5px">
                <el-form-item>
                  <div v-for="(item,index) in rightData.rightFunctionVO.tFunctionList" :key="index" class="hang" name="type" style="width:200%">
                    <el-col :span="3"><span>
                      {{item.funName}}：
                    </span></el-col>
                    <el-col :span="21"><span>
                      <el-checkbox-group v-model="dataForm.tFunctionList[index].value" v-bind:disabled="modify">
                      <el-checkbox :label="item.funId*1000+item2.rightId" v-for="(item2,index2) in rightData.rightFunctionVO.tRightList" :key="index2">{{item2.rightName}}</el-checkbox>
                    </el-checkbox-group>
                    </span></el-col>
                  </div>
                </el-form-item>
              </span>
            </div>
          </div>
        </el-form>
        <div v-if="!modify" slot="footer" class="dialog-footer">
          <el-button :size="size" type="primary" @click.native="modifySubmitForm" :loading="editLoading" style="width:100px;margin:0 auto;display:block">确定</el-button>
        </div>  
      </div>
        <!-- <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="dialogVisible = false">确 定</el-button>
        </span> -->
      </el-dialog>
    </div>
  </div>
</template>

<script>

export default {
  data() {
      return {
        size: "small",
        input: '',
        page: 1, //当前页
        perPage: 10, //每页多少条数据
        total: 0, //总共多少条数据
        startUseValue:true,
        tableData: [],
        multipleSelection: [],
        operation: false, // true:新增, false:编辑
        dialogVisible: false, // 新增编辑界面是否显示
        editLoading: false,
        dataFormRules: {
            roleName: [{ required: true, message: "请输入角色名", trigger: "blur" }],
        },
        dataFormAdd:{
          roleName:'',
          roleCreater:'',
        },
        // 权限修改
        modifyVisible: false, 
        dataForm: {
          roleName: "",
          tFunctionList:[],
          tMenuList:[],
          tPageList:[]
        },
        filters: {
          name: ""
        },
        rightData: {
          rightFunctionVO: { tFunctionList: [], tRightList: [] },
          rightMenuVO: { tMenuList: [], tRightList: [] },
          rightPageVO: { tPageList: [], tRightList: [] }
        },
        cmodify: 1,
        eleType: {
          fun: 1,
          menu: 2,
          page: 3,
          source: 4
        },
      }
    },
    methods: {
      selectRadio() {
        if (this.cmodify == 1) {
          this.modify = true;
        } else {
          this.modify = false;
        }
      },
      // 查询功能
      findByName: function() {
        if(this.input){
          this.$api.role.queryByName(this.input).then(res => {
          console.log(res);
          this.tableData = res.data;
          this.total = this.tableData.length
        });
        }
        else{
          this.findPage();
          this.getCount();
        }
      },
      // 获取分页数据
      findPage: function() {
        this.$api.role.findByPage(this.page, this.perPage).then(res => {
          this.tableData = res.data.roleList;
          // console.log(this.tableData);
        });
      },
      // 获取总量
      getCount: function() {
        this.$api.role.count().then(res => {
          this.total = res.data.totalSize;
        });
      },
      // 获取权限清单
      queryRoleRel() {
        this.$api.role.queryRoleRel().then(res => {
          let dataForm = { tMenuList: [], tPageList: [], tFunctionList: [] };
          this.rightData = res.data;
          dataForm["tMenuList"] = res.data.rightMenuVO.tMenuList.map(x => {
            return { value: x.menuId * 1000, eid: x.menuId, rid: null };
          });
          dataForm["tPageList"] = res.data.rightPageVO.tPageList.map(x => {
            return { value: x.pageId * 1000, eid: x.pageId, rid: null };
          });
          let aaa = [];
          for (
            let i = 0;
            i < this.rightData.rightFunctionVO.tFunctionList.length;
            i++
          ) {
            let value = [];
            let rid = [];
            for (var j = 0; j < res.data.rightFunctionVO.tRightList.length; j++) {
              value.push(
                res.data.rightFunctionVO.tFunctionList[i].funId * 1000 +
                  res.data.rightFunctionVO.tRightList[j].rightId.toString()
              );
              rid.push(res.data.rightFunctionVO.tRightList[j].rightId);
            }
            aaa.push({
              value: value,
              eid: res.data.rightFunctionVO.tFunctionList[i].funId,
              rid: rid
            });
          }

          dataForm["tFunctionList"] = aaa;
          // console.log(dataForm.tMenuList);
          // console.log("总体数据");

          // console.log(dataForm.tMenuList);
          this.temp = this.deepClone(dataForm);
          this.dataForm = this.deepClone(dataForm);
          // console.log(this.temp);
        });
      },
      //改变每页多少条数据
      handleperPageChange(val) {
        this.perPage = val;
        this.findPage()
      },
      // 分页查询
      handleCurrentChange(val) {
        this.page = val;
        this.findPage()
      },
      // 新增角色
      addRoleClick() {
        this.dialogVisible = true;
        this.operation = true;
        this.dataFormAdd = {
            roleName: "",
        };
      },
      // 编辑
      editRoleClick(row) {
        this.dialogVisible = true;
        this.operation = false;
        console.log(row);
        this.dataFormAdd = Object.assign({}, row);
      },
      // 修改
      modifyClick(row) {
        this.modifyVisible = true
        console.log(row);
        this.getQueryRoleRelById(row)
      },
      // 删除
      deleteRoleClick(row) {
        this.$confirm("确认删除选中记录吗？", "提示", {
            type: "warning"
        }).then(() => {
            console.log(row);
            this.$api.role.deleteRole(row.roleId).then(res => {
            this.page = 1;
            this.findPage();
            this.getCount();
            this.$message({ message: "删除成功", type: "success" });
            console.log(res);
            });
        }).catch(() => {});
      },
      // 新增/编辑 表单提交
      submitForm() {
        this.dataFormAdd.roleCreater = sessionStorage.getItem('user');
         this.$refs.dataForm.validate(valid => {
          if (valid) {
            this.$confirm("确认提交吗？", "提示", {}).then(() => {
              if (this.operation) {
                this.$api.role.addRole(this.dataFormAdd).then(res => {
                  this.editLoading = false;
                  if (res.code == 200) {
                    this.$message({ message: "操作成功", type: "success" });
                    this.dialogVisible = false;
                    this.$refs["dataForm"].resetFields();
                    console.log(this.dataFormAdd);
                  } else {
                    this.$message({
                      message: "操作失败, " + res.msg,
                      type: "error"
                    });
                  }
                  this.findPage();
                  this.getCount();
                });
              } else {
                this.$api.role.updateRole(this.dataFormAdd).then(res => {
                  this.editLoading = false;
                  if (res.code == 200) {
                    this.$message({ message: "操作成功", type: "success" });
                    this.dialogVisible = false;
                    this.$refs["dataForm"].resetFields();
                    console.log(res.data);
                  } else {
                    this.$message({
                      message: "操作失败, " + res.msg,
                      type: "error"
                    });
                  }
                  this.findPage();
                  this.getCount();
                });
              }
            }).catch(() => {});
          }
        });
      },
      // 权限修改（表单提交）
      modifySubmitForm: function() {
        this.$confirm("确认提交吗？", "提示", {}).then(() => {
          var newdata = {};
          newdata.roleId = this.dataForm.roleId;
          newdata.tRoleRightRelList = [];
          this.dataForm.tMenuList.map(x => {
            let rid = x.value % 1000;
            if (rid) {
              console.log(rid);
              newdata.tRoleRightRelList.push({
                eleId: x.eid,
                eleType: this.eleType.menu,
                rightId: Number(rid),
                roleId: newdata.roleId
              });
            }
          });

          this.dataForm.tPageList.map(x => {
            let rid = x.value % 1000;
            if (rid) {
              newdata.tRoleRightRelList.push({
                eleId: x.eid,
                eleType: this.eleType.page,
                rightId: Number(rid),
                roleId: newdata.roleId
              });
            }
          });

          this.dataForm.tFunctionList.map(x => {
            x.value.map(y => {
              if (typeof y == "number") {
                var eid = parseInt(y / 1000);
                var rid = y % 1000;
                newdata.tRoleRightRelList.push({
                  eleId: eid,
                  eleType: this.eleType.fun,
                  rightId: rid,
                  roleId: newdata.roleId
                });
              }
            });
          });
          this.$api.role.updateRole(newdata).then(res => {
            this.editLoading = false;
            if (res.code == 200) {
              this.$message({ message: "操作成功", type: "success" });
              this.modifyVisible = false
              console.log(res.data);
            } else {
              this.$message({
                message: "操作失败, " + res.msg,
                type: "error"
              });
            }
          });
        }).catch(() => {});
      },
      handleClose(done) {
        done();
      },
      // 深度赋值
      deepClone(data) {
        // let   gettype=Object.prototype.toString
        let type = this.getDataType(data);
        let obj;

        if (type === "array") {
          obj = [];
        } else if (type === "object") {
          obj = {};
        } else {
          //不再具有下一层次
          return data;
        }
        if (type === "array") {
          for (let i = 0, len = data.length; i < len; i++) {
            obj.push(this.deepClone(data[i]));
          }
        } else if (type === "object") {
          for (let key in data) {
            obj[key] = this.deepClone(data[key]);
          }
        }
        return obj;
      },
      getDataType: function(o) {
        if (o === null) {
          return "null";
        } else if (typeof o == "object") {
          if (typeof o.length == "number") {
            return "array";
          } else {
            return "object";
          }
        } else {
          return "param is no object type";
        }
      },
      // 根据角色ID获取角色关联信息
      getQueryRoleRelById(row) {
        this.$api.role.queryRoleRelById(row.roleId).then(res => {
            let dataForm2 = this.deepClone(this.temp);
            dataForm2.roleId = res.data.roleId;
            dataForm2.roleName = res.data.roleName;
            let menu, mdata;
            for (menu in res.data.tMenuList) {
              menu = res.data.tMenuList[menu];
              for (mdata in dataForm2.tMenuList) {
                if (dataForm2.tMenuList[mdata].eid == menu.menuId) {
                  dataForm2.tMenuList[mdata].rid = menu.rightId;
                  dataForm2.tMenuList[mdata].value =
                    Number(dataForm2.tMenuList[mdata].eid) * 1000 +
                    Number(dataForm2.tMenuList[mdata].rid);
                }
              }
            }
            for (menu in res.data.tPageList) {
              menu = res.data.tPageList[menu];
              for (mdata in dataForm2.tPageList) {
                if (dataForm2.tPageList[mdata].eid == menu.pageId) {
                  dataForm2.tPageList[mdata].rid = menu.rightId;
                  dataForm2.tPageList[mdata].value =
                    Number(dataForm2.tPageList[mdata].eid) * 1000 +
                    Number(dataForm2.tPageList[mdata].rid);
                }
              }
            }
            let sorted = this.groupBy(res.data.tFunctionList, function(item) {
              return [item.funId];
            });
            let olddata = dataForm2.tFunctionList;
            let l = [];
            var eids = [];
            olddata.forEach(x => {
              sorted.forEach(os => {
                let data = { value: [], eid: "", rid: [] };
                let value = [];
                let rid = [];
                let eid = "";
                os.forEach(o => {
                  value.push(Number(o.funId) * 1000 + Number(o.rightId));
                  rid.push(o.rightId);
                  eid = o.funId;
                });
                data.value = value;
                data.eid = eid;
                data.rid = rid;
                if (x.eid == eid) {
                  l.push(data);
                  eids.push(eid);
                  return 1;
                }
              });
            });
            olddata.forEach(x => {
              if (!eids.includes(x.eid)) {
                l.push(x);
              }
            });
            dataForm2.tFunctionList = l;
            this.dataForm = this.deepClone(dataForm2);
            dataForm2 = {};
            console.log("个人数据");
            console.log(this.dataForm);
          });
        },
      groupBy(array, f) {
        if (!array) {
          return [];
        }

        let groups = {};
        array.forEach(function(o) {
          let group = JSON.stringify(f(o));
          groups[group] = groups[group] || [];
          groups[group].push(o);
        });
        return Object.keys(groups).map(function(group) {
          return groups[group];
        });
      },
    },
    mounted() {
      this.findPage();
      this.getCount();
      this.queryRoleRel();
    }
}
</script>

<style lang="less" scoped>
.common_title {
    margin-top: 20px;
}
.query_bg {
    height: 80px;
    line-height: 80px;
    margin-top: 10px;
    //   background-color: hotpink;
    .el-button--goon {
      color: #FFF;
      background-color: #37508D;
      border-color: #37508D;
    }

    .el-input, .el-select {
        width: 140px;
    }
}

.dataList_bg {
      height: 90%;
      margin-top: 5px;
    //   background-color: lawngreen;
}

</style>
